package app

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"tech-service/config"
	"tech-service/pkg/database"
	"tech-service/pkg/logbase"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Application struct {
	Config *config.Config
	DB     *gorm.DB
	Router *gin.Engine
}

func InitApplication(filename string) *Application {
	// 加载配置文件
	config, err := config.LoadConfig(filename)
	if err != nil {
		log.Fatal(err)
	}

	// 初始化MySQL日志
	sqlLogger := logbase.NewMySQLLogger(
		logbase.WithLogLevel(logbase.InfoLevel),         // 设置日志级别
		logbase.WithSlowThreshold(100*time.Millisecond), // 设置慢查询阈值
		logbase.WithColors(true),                        // 启用颜色输出
		logbase.WithWriter(os.Stdout),
	)
	//初始化mysql
	db, err := database.InitDataBase(config.Mysql, sqlLogger)
	if err != nil {
		log.Fatal(err)
	}
	//初始化gin
	router := createGinApp()

	return &Application{
		Config: config,
		DB:     db,
		Router: router,
	}
}

// 创建Fiber应用
func createGinApp() *gin.Engine {
	router := gin.Default()
	//设置静态资源服务
	router.StaticFS("/static", http.Dir("./static"))

	return router
}
func (app *Application) StartServer() {
	fmt.Println("==============启动中==============")
	// 创建 http.Server 实例
	srv := &http.Server{
		Addr:    fmt.Sprintf(":%d", app.Config.System.Port),
		Handler: app.Router, // 关键: 使用 Gin 的 Router 作为 Handler
	}

	idleConnsClosed := make(chan struct{})

	go func() {
		sigint := make(chan os.Signal, 1)
		signal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM)
		<-sigint

		log.Println("==============启动完成==============")

		// 使用带超时的 Context 控制关闭等待时间
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()

		// 调用 http.Server 的 Shutdown 方法（不是 app.Router）
		if err := srv.Shutdown(ctx); err != nil {
			log.Printf("Server shutdown error: %v", err)
		}

		close(idleConnsClosed)
	}()

	// 使用 srv.ListenAndServe() 替代 app.Router.Run()
	log.Printf("Server starting on :%d", app.Config.System.Port)
	if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatalf("Server failed to start: %v", err)
	}

	<-idleConnsClosed
	log.Println("Server gracefully stopped")
}

func (a *Application) Cleanup() {
	if sqlDB, err := a.DB.DB(); err == nil {
		if err := sqlDB.Close(); err != nil {
			log.Printf("MySQL connection close error: %v", err)
		}
	}

	// if err := a.Redis.Close(); err != nil {
	// 	log.Printf("Redis connection close error: %v", err)
	// }
}
